import { register } from 'yt-engine' 
import customs from './debug' 

function resolvePath(paths) { 
  const last = paths.length - 1 
  const version = paths[last - 1] 
  const name = paths[last - 2] 

  return [ name, version ] 
} 

function resolveNameVersion(ctx, callback) { 
  ctx.keys().forEach(key => { 
    // 注册组件 
    const paths = key.split('/') 

    if(paths.length < 3) { 
      return 
    } 

    const [ name, version ] = resolvePath(paths) 

    if(isNaN(parseInt(version))) { return } 

    callback({ name, version, path: key }) 
  }) 
} 

const coms = {} 

function setName(name,version) {
  return `${name}@${version}`
}

// js
;((ctx) => { 
  resolveNameVersion(ctx, ({ name, version, path }) => { 

    const Class = ctx(path).default 

    let comName = setName(name,version)

    coms[comName] = {
      name: comName, 
      version, 
      clazzType: name
    }

    register({ 
      name, 
      version, 
      module: Class 
    }) 
  }) 
})(require.context('packages', true, /index\.(js|ts)x?$/)) 

// xml
;((ctx) => { 
  // 解析xml显示在界面上 
  resolveNameVersion(ctx, ({ name, version, path }) => { 
    const xml = ctx(path) 

    const comName = setName(name,version)

    if(coms[comName]) {
      coms[comName].xml = xml
    } else {
      coms[comName] = {
        name: comName, 
        version, 
        clazzType: name,
        xml
      }
    }
  }) 
})(require.context('packages', true, /config.xml$/)) 

export default Object.values(coms).concat(Object.values(customs))
